package com.ruoyix.generator.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyix.common.utils.StringUtils;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyix.generator.util.PomXmlUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyix.generator.domain.bo.GenModuleBo;
import com.ruoyix.generator.domain.vo.GenModuleVo;
import com.ruoyix.generator.domain.GenModule;
import com.ruoyix.generator.mapper.GenModuleMapper;
import com.ruoyix.generator.service.IGenModuleService;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 模块管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-08
 */
@RequiredArgsConstructor
@Service
public class GenModuleServiceImpl implements IGenModuleService {

    private final GenModuleMapper baseMapper;

    /**
     * 查询模块管理
     */
    @Override
    public GenModuleVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询模块管理列表
     */
    @Override
    public TableDataInfo<GenModuleVo> queryPageList(GenModuleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GenModule> lqw = buildQueryWrapper(bo);
        Page<GenModuleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询模块管理列表
     */
    @Override
    public List<GenModuleVo> queryList(GenModuleBo bo) {
        LambdaQueryWrapper<GenModule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GenModule> buildQueryWrapper(GenModuleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GenModule> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getModuleCode()), GenModule::getModuleCode, bo.getModuleCode());
        lqw.like(StringUtils.isNotBlank(bo.getModuleName()), GenModule::getModuleName, bo.getModuleName());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), GenModule::getDescription, bo.getDescription());
        lqw.like(StringUtils.isNotBlank(bo.getMainClassName()), GenModule::getMainClassName, bo.getMainClassName());
        lqw.eq(StringUtils.isNotBlank(bo.getCurrentVersion()), GenModule::getCurrentVersion, bo.getCurrentVersion());
        lqw.eq(StringUtils.isNotBlank(bo.getUpgradeInfo()), GenModule::getUpgradeInfo, bo.getUpgradeInfo());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), GenModule::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), GenModule::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增模块管理
     */
    @Override
    public Boolean insertByBo(GenModuleBo bo) {
        GenModule add = BeanUtil.toBean(bo, GenModule.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模块管理
     */
    @Override
    public Boolean updateByBo(GenModuleBo bo) {
        GenModule update = BeanUtil.toBean(bo, GenModule.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GenModule entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除模块管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public int generateModule(String path, String moduleCode,String moduleName) {
        File parentPomFile = findParentPomFile(path);
        if (parentPomFile == null) {
            throw new RuntimeException("未找到父POM文件，请确保目录中包含有效的Maven项目结构。");
        }

        // 创建子模块目录
        File moduleDir = new File(parentPomFile.getParent(), moduleName);
        if (moduleDir.exists()) {
            throw new RuntimeException(moduleDir.getAbsolutePath() + "路径已存在，请删除后重新尝试");
        }

        moduleDir.mkdirs();

        // 创建目录结构
        createDirectoryStructure(moduleDir, moduleCode);

        // 创建 pom.xml 文件
        createPomFile(moduleDir, moduleName);

        // 创建 README.md 文件
        createReadmeFile(moduleDir);

        createBackup(parentPomFile,moduleDir);

        // 更新父POM文件
        updateParentPom(parentPomFile, moduleName);

        return 1;
    }

    private File findParentPomFile(String path) {
        File directory = new File(path);
        while (directory != null) {
            File pomFile = new File(directory, "pom.xml");
            if (pomFile.exists()) {
                return pomFile;
            }
            directory = directory.getParentFile();
        }
        return null;
    }

    private void createDirectoryStructure(File moduleDir, String moduleCode) {
        createDirectory(moduleDir, "src/main/java/com/ruoyix/" + moduleCode + "/controller");
        createDirectory(moduleDir, "src/main/java/com/ruoyix/" + moduleCode + "/service");
        createDirectory(moduleDir, "src/main/java/com/ruoyix/" + moduleCode + "/service/impl");
        createDirectory(moduleDir, "src/main/java/com/ruoyix/" + moduleCode + "/mapper");
        createDirectory(moduleDir, "src/main/java/com/ruoyix/" + moduleCode + "/domain");
        createDirectory(moduleDir, "src/main/resources/mapper." + moduleCode);
    }

    private void createDirectory(File parentDir, String dirPath) {
        File directory = new File(parentDir, dirPath);
        directory.mkdirs();
    }

    private void createPomFile(File moduleDir, String moduleName) {
        File pomFile = new File(moduleDir, "pom.xml");
        try (FileWriter writer = new FileWriter(pomFile)) {
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
                "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
                "    <parent>\n" +
                "        <artifactId>ruoyi-x-vue</artifactId>\n" +
                "        <groupId>com.ruoyix</groupId>\n" +
                "        <version>4.8.1</version>\n" +
                "    </parent>\n" +
                "    <modelVersion>4.0.0</modelVersion>\n" +
                "\n" +
                "    <artifactId>" + moduleName + "</artifactId>\n" +
                "\n" +
                "    <properties>\n" +
                "        <maven.compiler.source>8</maven.compiler.source>\n" +
                "        <maven.compiler.target>8</maven.compiler.target>\n" +
                "    </properties>\n" +
                "\n" +
                "    <dependencies>\n" +
                "        <dependency>\n" +
                "            <groupId>com.ruoyix</groupId>\n" +
                "            <artifactId>ruoyi-x-common</artifactId>\n" +
                "        </dependency>\n" +
                "    </dependencies>\n" +
                "\n" +
                "</project>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createReadmeFile(File moduleDir) {
        File readmeFile = new File(moduleDir, "README.md");
        try (FileWriter readmeWriter = new FileWriter(readmeFile)) {
            readmeWriter.write("## 使用方式\n" +
                "1. 右键点击生成模块pom.xml文件，选择 Add as Maven Project\n" +
                "2. 选择 admin 模块下 pom.xml 文件，在 <dependencies> 标签中引入生成模块");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void createBackup(File parentPomFile, File backupDirectory) {
        try {
            File backupFile = new File(backupDirectory, "pom.xml.backup");

            // 复制原始POM文件到备份文件
            Files.copy(parentPomFile.toPath(), backupFile.toPath());

            // 如果需要，你还可以在备份文件名中添加时间戳以进行版本管理
            // File timestampedBackupFile = new File(backupDirectory, "pom.xml.backup." + System.currentTimeMillis());
            // Files.copy(parentPomFile.toPath(), timestampedBackupFile.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateParentPom(File parentPomFile, String moduleName) {
        File pomFile = new File(parentPomFile.getPath());
        PomXmlUtils pomXmlUtils = new PomXmlUtils(pomFile);
        String module = moduleName;

        // 添加到 <modules> 下
        pomXmlUtils.addModule(module);
        // 添加新的 <dependency> 元素
        String groupId = "com.ruoyix";
        String artifactId = moduleName;
        String version = "${ruoyi-x-vue.version}";

        pomXmlUtils.addDependency(groupId, artifactId, version);

        // 保存更改到原始 POM 文件
        pomXmlUtils.saveChanges();
    }


}
